//#version 300 es

precision highp float;
precision lowp int;

const float PI = 3.14159265358979323846264;
const float _2PI = 6.2831853071796;
varying vec2 vUv;
varying vec3 vWorldNorm;
varying vec3 vViewDir;
varying vec4 vViewPos;
varying vec4 vWorldPos;
varying vec3 vDisp;
varying float fDeep;
//
uniform sampler2D texBaseColor;
uniform sampler2D texNormal;
uniform sampler2D texSky;
uniform sampler2D texUnderWater;
uniform sampler2D texWaveDetail;
//预计算的贴图
uniform sampler2D texPrefilterdEnv;
uniform sampler2D texPrefilterDiff;
uniform float u_hdrexposure;
uniform mat4 irrad_mat_red;
uniform mat4 irrad_mat_green;
uniform mat4 irrad_mat_blue;							
uniform float u_curTm;
vec3 u_lightColor = vec3(1.,1.,1.);
vec3 u_diffuseColor = vec3(0.1,0.1,0.1);
vec3 speccontrib = vec3(0.);

const float _maxu8 = 255.0;
const float _maxu16 = 65535.0;
const float _shift8 = 256.0;    //平移的话是*256而不是255
vec2 _RGBAToU16(const in vec4 rgba){
    return vec2((rgba.r*_maxu8+rgba.g*_maxu8*_shift8)/_maxu16, (rgba.b*_maxu8+rgba.a*_maxu8*_shift8)/_maxu16);
}
vec3 _RGBEToRGB( const in vec4 rgba ){
    float f = pow(2.0, rgba.w * 255.0 - (128.0 + 8.0));
    return rgba.rgb * (255.0 * f);
}

float saturate(float v){
    return min(max(v,0.),1.);
}

/*
* 对一个全景图进行采样。假设x轴指向中心。
*/
vec4 texPanorama(sampler2D tex, const in vec3 dir){
	float envu = atan(dir.z,dir.x)/_2PI+0.5; 	
	float envv = acos(dir.y)/PI;//(1.0-dir.y)/2.0;
	return texture2D(tex,vec2(envu,envv));
}

vec4 calcWaterC(vec3 view, vec3 normal){
	//深度系数，1表示光线无法到达
	float deepk = min(2.*fDeep/10.,1.);
	//越深则水本身颜色越强
	vec3 fracColor = mix(vec3(.0),vec3(.1,.1,.4),deepk);	
	//vec3 refracC = vec3(1.0);//texPanorama(texUnderWater,-view).rgb;
	float F0=0.15;
	float von = dot(view,normal);
	//菲涅尔，越大反射越强
	float f =  F0+(1.0-F0)*exp2((-5.55473*von-6.98316)*von);
	//能看到水底的程度。反射剩余的*水中的衰减
	float a = (1.-f)*(1.-deepk);
	vec3 ref = texPanorama(texSky, reflect(-view,normal)).rgb*f;
	return vec4(fracColor+ref,1.-a);// vec3(f);//mix(refracC,ref,f);
}

void main() {
    vec3 normal =  normalize(vWorldNorm);
	vec3 smoothnorm = normal;
	vec4 normtex = texture2D( texNormal, vUv );
    vec3 view   = -normalize(vViewDir);
    float NoV = saturate(dot( view, normal ));
    vec3 R = 2. * NoV * normal - view;
	vec4 wc = calcWaterC(view, normal);

    gl_FragColor.rgb = vec3(fract(vUv*10.),1.);// wc.rgb;//texture2D(texWaveDetail,vUv).rgb;// fracColor * texture2D(texUnderWater, vUv*20.0).rgb;// vec3(1.0);//pbrl.rgb;
    gl_FragColor.a = 1.0;//wc.a;
}
